package common.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class BitmapHelper {
    public static final int[] getBitmapOfSize(String fileName) {
        int[] sizes = new int[2];
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(fileName, options);
            sizes[0] = options.outWidth;
            sizes[1] = options.outHeight;
            return sizes;
        } catch (Exception e) {
            sizes[0] = sizes[1] = -1;
        }
        return sizes;
    }

    public static final int getBitmapOfWidth(String fileName) {
        return getBitmapOfSize(fileName)[0];
    }

    public static final int getBitmapOfHeight(String fileName) {
        return getBitmapOfSize(fileName)[1];
    }

    public static final Bitmap decodeFile(String fileName, int width, int height) {
        Options options = new Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileName, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateInSampleSize(options, width, height);
        return BitmapFactory.decodeFile(fileName, options);
    }

    private static final int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }

            final float totalPixels = width * height;
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }
}
